import parse from '@/utils/parse';

export default [
  {
    name: '用户信息',
    method: 'userInfo',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'users',
        query => query.equalTo('objectId', data)
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            phone: item.get('phone'),
            address: item.get('address'),
            // avatar: item.get('avatar')._url,
            nickname: item.get('nickname')
          }));
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '根据手机号查找用户',
    method: 'queryUserByPhone',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'users',
        query => query.equalTo('phone', data)
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            userId: item.id
          }));
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '当前用户默认选中学生',
    method: 'query_default_student'
    , excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'students',
        query => {
          query.equalTo('user_id', data);
          query.equalTo('is_default', 1);
        }
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            class: item.get('class'),
            name: item.get('name'),
            school: item.get('school'),
            word_count: item.get('word_count'),
            gold_coin: item.get('gold_coin'),
          }))[0];
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '当前用户所有学生',
    method: 'query_student_list'
    , excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'students',
        query => {
          query.equalTo('user_id', data);
        }
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            class: item.get('class'),
            name: item.get('name'),
            school: item.get('school'),
            is_default: item.get('is_default'),
          }));
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '当前学生',
    method: 'query_student'
    , excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'students',
        query => {
          query.equalTo('objectId', data);
        }
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            class: item.get('class'),
            name: item.get('name'),
            school: item.get('school'),
            is_default: item.get('is_default'),
          }))[0];
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '删除学生',
    method: 'delete_student'
    , excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'students',
        query => query.equalTo('objectId', data)
      ).filter(x => x.type && x.type === 'result')
        .map(x => x.result[0])
        .subscribe(function (res) {
          parse.delete(res).subscribe(fn, errFn)
        }, errFn);;
    }
  },
  {
    name: '用户登录',
    method: 'loginUser',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'users',
        query => query.equalTo('phone', data.phone)
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            userId: item.id
            , password: item.get('password')
            , phone: item.get('phone')
          }));
        })
        .subscribe(function (res) {
          // console.log("res::", res);
          if (!!res && res.length > 0) {//账号存在（用户）
            let _user = res[0];
            if (_user.password == data.password) {
              fn({ status: 200, msg: '登录成功！', data: { userId: _user.userId } });
            } else {
              errFn({ status: 200011, msg: '密码错误，请重新输入！' });
            }
            return;
          }
          errFn({ status: 200012, msg: '用户不存在，请重新输入！' });
        }, errFn);
    }
  },
  {
    name: '新增用户',
    method: 'addUser',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'users',
        query => query.equalTo('phone', data.phone)
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            userId: item.id
          }));
        })
        .subscribe(function (res) {

          if (!!res && res.length > 0) {
            errFn({ status: 200010, msg: '当前手机号已被使用！' });
            return;
          }
          parse.create('users', data)
            .map(x => {
              return { userId: x.id, phone: data.phone };
            })
            .subscribe(fn, errFn);
        }, errFn);
    }
  },
  {
    name: '地址信息',
    method: 'addressInfo',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'addresses',
        query => query.equalTo('user_id', data)
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            phone: item.get('phone'),
            address: item.get('address'),
            username: item.get('username'),
            user_id: item.get('user_id'),
            province: item.get('province'),
            province_code: item.get('province_code'),
            city: item.get('city'),
            city_code: item.get('city_code'),
            area: item.get('area'),
            area_code: item.get('area_code'),
          }));
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '保存地址',
    method: 'addAddress',
    excute: ({ data, fn, errFn } = {}) => {
      parse.create('addresses', data)
        .map(x => {
          return { id: x.id };
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '查询学生人数',
    method: 'queryStudentCountByUserId'
    , excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'students',
        query => query.equalTo('user_id', data)
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          // console.log("x.result2::", x.result);
          return { count: x.result.length };
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '新增学生',
    method: 'add_student',
    excute: ({ data, fn, errFn } = {}) => {
      //查询改用户名下所有学生，将其状态改成非默认，将新增学生设置为默认
      parse.query(
        'students',
        query => query.equalTo('user_id', data.user_id)
      ).filter(x => x.type && x.type === 'result')
        .map(x => x.result)
        .subscribe(next => {
          if (next.length == 0) {
            parse.create('students', data)
              .map(x => {
                return { studentId: x.id };
              })
              .subscribe(fn, errFn);
          } else {
            //将学生状态改成非默认
            const promises = next.map(item => new Promise(resolve => {
              parse.update(item, {
                is_default: 0
              }).subscribe(resolve);
            }))
            Promise.all(promises).then(res => {
              parse.create('students', data)
                .map(x => {
                  return { studentId: x.id };
                })
                .subscribe(fn, errFn);
            })
          }
        });
    }
  },
  {
    name: '修改学生',
    method: 'update_student',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'students',
        query => query.equalTo('objectId', data.id)
      ).filter(x => x.type && x.type === 'result')
        .map(x => x.result[0])
        .subscribe(next => {
          parse.update(next, data).subscribe(fn, errFn);
        }, errFn);
    }
  },
  {
    name: '修改默认学生',
    method: 'update_default_student',
    excute: ({ data, fn, errFn } = {}) => {
      //查询改用户名下所有学生，将其状态改成非默认
      parse.query(
        'students',
        query => query.equalTo('user_id', data.user_id)
      ).filter(x => x.type && x.type === 'result')
        .map(x => x.result)
        .subscribe(next => {
          if (next.length == 0) {
            parse.create('students', data)
              .map(x => {
                return { studentId: x.id };
              })
              .subscribe(fn, errFn);
          } else {
            //将非当前学生状态改成非默认
            const promises = next.map(item => new Promise(resolve => {
              parse.update(item, {
                is_default: data.id != item.id ? 0 : 1
              }).subscribe(resolve);
            }))
            Promise.all(promises).then(res => {
              fn('success');
            })
          }
        });
    }
  },
  {
    name: '保存地址',
    method: 'updateAddress',
    excute: ({ data, fn, errFn } = {}) => {
      const address = parse.query(
        'addresses',
        query => query.equalTo('user_id', data.user_id)
      ).filter(x => x.type && x.type === 'result').subscribe(res => {
        console.log("address:", res);
        parse.update(res.result[0], data).subscribe(fn, errFn);
      }, errFn);

    }
  },
  {
    name: '保存用户',
    method: 'updateUser',
    excute: ({ data, fn, errFn } = {}) => {


      parse.query(
        'users',
        query => query.equalTo('phone', data.phone)
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            userId: item.id
          }));
        })
        .subscribe(function (res) {

          if (!!res && res.length > 0) {
            errFn({ status: 200010, msg: '当前手机号已被使用！' });
            return;
          }
          const users = parse.query(
            'users',
            query => query.equalTo('objectId', data.id)
          ).filter(x => x.type && x.type === 'result').subscribe(res => {
            // console.log("users:", res.result[0]);
            // var item = { phone: data.phone }
            parse.update(res.result[0], data).subscribe(fn, errFn);
          }, errFn);
        }, errFn);
    }
  },
  {
    name: '修改学生所获金币数',
    method: 'update_student_gold',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('students', query => query.equalTo('objectId', data.student_id))
        .filter(x => x.type && x.type === 'result')
        .map(x => x.result[0])
        .subscribe(res => {
          const get_gold_coin = (res.get('get_gold_coin') || 0) + data.get_gold_coin;
          parse.update(res, { get_gold_coin, gold_coin: get_gold_coin }).subscribe(fn, errFn);
        });
    }
  },
  {
    name: '修改学生阅读字数',
    method: 'update_student_words',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('students', query => query.equalTo('objectId', data.student_id))
        .filter(x => x.type && x.type === 'result')
        .map(x => x.result[0])
        .subscribe(res => {
          const read_word_count = (res.get('read_word_count') || 0) + data.read_word_count;
          parse.update(res, { read_word_count, word_count: read_word_count }).subscribe(fn, errFn);
        });
    }
  },
]